﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using KeRui.Common;
using KeRui.Upload;
using System.IO;

public partial class Manage_Seller_AdItem : System.Web.UI.Page
{
    protected KeRui.BLL.Ad bllAd;
    protected KeRui.Model.Ad modelAd = new KeRui.Model.Ad();
    public string Act = ManageHelper.PageAct();
    private ManageErrMsg nsb = new ManageErrMsg();
    protected string ActFlag = "addsave";
    protected string ActName = "添加";
    protected int state = -1;
    protected DataSet dsCmsSite = new DataSet();
    protected KeRui.BLL.CmsSite bllCmsSite = new KeRui.BLL.CmsSite();
    protected int SiteID = -1;
    protected KeRui.BLL.SellerAD bllASellerAD = new KeRui.BLL.SellerAD();
    protected void Page_Load(object sender, EventArgs e)
    {
        ManageHelper.CheckAdminLogin();//登陆判断
        state = PageRequest.GetInt("state", -1);
        SiteID = PageRequest.GetInt("SiteID", -1);
        if (SiteID == -1)
        {
            //nsb.AddErr("没有选择站点。"); nsb.ChkErr();
        }
        dsCmsSite = bllCmsSite.GetDataSet();
        bllAd = new KeRui.BLL.Ad();
        switch (Act)
        {
            case "addsave":
                AdAdd();
                break;
            case "edit":
                Edit();
                break;
            case "editsave":
                EditSave();
                break;
            case "del":
                Del();
                break;
            case "state":
                State();
                break;
            case "ref":
                Ref();
                break;
            default:
                break;
        }
    }


    #region 添加
    private void AdAdd()
    {
        ManageHelper.CheckAdminPower("site_adadd_" + SiteID);//权限
        #region 获取提交信息
        modelAd.SiteID = PageRequest.GetInt("SiteID", -1);
        if (SiteID == -1)
        {
            nsb.AddErr("请选择站点。");
        }
        modelAd.AdName = PageRequest.GetString("AdName");
        if (modelAd.AdName == "")
        {
            nsb.AddErr("广告名称。");
        }
        modelAd.PersonInCharge = PageRequest.GetString("PersonInCharge");
        if (modelAd.PersonInCharge == "")
        {
            nsb.AddErr("广告负责人。");
        }
        modelAd.AdWidth = PageRequest.GetInt("AdWidth", -1);
        if (modelAd.AdWidth == -1)
        {
            nsb.AddErr("广告的宽应是一个正整数。");
        }
        modelAd.AdHight = PageRequest.GetInt("AdHight", -1);
        if (modelAd.AdHight == -1)
        {
            nsb.AddErr("广告的高应是一个正整数。");
        }
        modelAd.AdType = PageRequest.GetInt("AdType", -1);
        if (modelAd.AdType == -1)
        {
            nsb.AddErr("Error：广告类别没有得到。");
            nsb.ChkErr();
        }
        modelAd.BuyNum = PageRequest.GetInt("BuyNum", -1);
        if (modelAd.BuyNum < 1)
        {
            nsb.AddErr("最小购买量应为一个大于0的正整数。");
        }
        modelAd.BuyUnit = PageRequest.GetInt("BuyUnit", -1);
        if (modelAd.BuyUnit == -1)
        {
            nsb.AddErr("请选择购买单位。");
        }

        #region 上传广告
        Upload upload = new Upload();
        UploadedFile upfile = upload.Files[0];
        modelAd.DefaultAdText = upfile.FileName;
        switch (modelAd.AdType)
        {
            case 1:
                modelAd.DefaultAdText = PageRequest.GetString("DefaultAdText");
                if (modelAd.DefaultAdText == "")
                {
                    nsb.AddErr("请填写广告信息。");
                } 
                break;
            case 2:
                if (modelAd.DefaultAdText == "")
                {
                    nsb.AddErr("请选择一个图片。");
                }
                else
                {
                    if (!ChkExt(upfile.Extension, 0))
                    {
                        nsb.AddErr("文件格式不正确。请选择一个图片");
                    }
                }
                break;
            case 3:
                if (modelAd.DefaultAdText == "")
                {
                    nsb.AddErr("请选择一个Flash。");
                }
                else
                {
                    if (!ChkExt(upfile.Extension, 1))
                    {
                        nsb.AddErr("文件格式不正确。请选择一个Flash。");
                    }
                }
                break;
            default: break;
        }
        nsb.ChkErr();
        if (modelAd.AdType > 1)
        {
            string fileExt = modelAd.DefaultAdText;
            string Path = CreatePathWithDate("/Upload/SellerAD/", "YY-MM:DD");
            modelAd.DefaultAdText = Path + System.Guid.NewGuid() + GetExt(upfile.Extension);
            upfile.SaveAs(Server.MapPath(modelAd.DefaultAdText)); //保存
        }
        #endregion

        modelAd.IsUsing = PageRequest.GetInt("IsUsing", 1) == 1 ? false : true;
        modelAd.CreateIP = Utils.GetRealIP();
        #endregion
        nsb.ChkErr();
        int RetFlag = bllAd.Add(modelAd);
        ManageHelper.AddLog("site_adadd_" + SiteID, "添加了“" + modelAd.AdName + "”广告。");

        KeRui.TemplateMaker.Publish publish = new KeRui.TemplateMaker.Publish();

        string publishInfo = publish.PublishAd(RetFlag, 1);

        if (publishInfo != "")
        {
            nsb.AddErr("数据已经添加到数据库。ERROR：" + publishInfo); nsb.ChkErr();
        }

        Response.Write("<script>location.href=\"AdList.aspx?siteid=" + modelAd.SiteID + "&sucmsg=添加成功。\";</script>");
    }
    #endregion

    #region 反显修改页面
    private void Edit()
    {
        ActFlag = "editsave";
        ActName = "修改";
        int AdID = PageRequest.GetInt("ID", -1);
        if (AdID == -1)
        {
            nsb.AddErr("Error:信息不存在。");
            nsb.ChkErr();
        }
        modelAd = bllAd.GetModel(AdID);
    }
    #endregion

    #region 修改时保存
    private void EditSave()
    {
        ManageHelper.CheckAdminPower("site_AdEdit_" + SiteID);//权限
        modelAd.AdID = PageRequest.GetInt("AdID", -1);
        if (modelAd.AdID == -1)
        {
            nsb.AddErr("ERR：信息不存在。");
        }
        KeRui.Model.Ad old_AdModel = bllAd.GetModel(modelAd.AdID);
        #region 获取提交信息
        modelAd.SiteID = PageRequest.GetInt("SiteID", -1);
        if (SiteID == -1)
        {
            nsb.AddErr("请选择站点。");
        }
        modelAd.AdName = PageRequest.GetString("AdName");
        if (modelAd.AdName == "")
        {
            nsb.AddErr("广告名称。");
        }
        modelAd.PersonInCharge = PageRequest.GetString("PersonInCharge");
        if (modelAd.PersonInCharge == "")
        {
            nsb.AddErr("广告负责人。");
        }
        modelAd.AdWidth = PageRequest.GetInt("AdWidth", -1);
        if (modelAd.AdWidth == -1)
        {
            nsb.AddErr("广告的宽应是一个正整数。");
        }
        modelAd.AdHight = PageRequest.GetInt("AdHight", -1);
        if (modelAd.AdHight == -1)
        {
            nsb.AddErr("广告的高应是一个正整数。");
        }
        modelAd.AdType = PageRequest.GetInt("AdType", -1);
        if (modelAd.AdType == -1)
        {
            nsb.AddErr("Error：广告类别没有得到。");
            nsb.ChkErr();
        }
        modelAd.BuyNum = PageRequest.GetInt("BuyNum", -1);
        if (modelAd.BuyNum < 1)
        {
            nsb.AddErr("最小购买量应为一个大于0的正整数。");
        }

        modelAd.BuyUnit = PageRequest.GetInt("BuyUnit", -1);
        if (modelAd.BuyUnit == -1)
        {
            nsb.AddErr("请选择购买单位。");
        }

        #region 上传广告
        Upload upload = new Upload();
        UploadedFile upfile = upload.Files[0];
        modelAd.DefaultAdText = upfile.FileName;
        switch (modelAd.AdType)
        {
            case 1:
                modelAd.DefaultAdText = PageRequest.GetString("DefaultAdText");
                if (modelAd.DefaultAdText == "")
                {
                    nsb.AddErr("请填写广告信息。");
                }
                break;
            case 2:
                if (modelAd.DefaultAdText == "")
                {

                }
                else
                {
                    if (!ChkExt(upfile.Extension, 0))
                    {
                        nsb.AddErr("文件格式不正确。请选择一个图片");
                    }
                }
                break;
            case 3:
                if (modelAd.DefaultAdText == "")
                {

                }
                else
                {
                    if (!ChkExt(upfile.Extension, 1))
                    {
                        nsb.AddErr("文件格式不正确。请选择一个Flash。");
                    }
                }
                break;
            default: break;
        }
        nsb.ChkErr();
        if (modelAd.DefaultAdText == "")
        {
            modelAd.DefaultAdText = old_AdModel.DefaultAdText;
        }
        else
        {
            if (modelAd.AdType > 1)
            {
                string fileExt = modelAd.DefaultAdText;
                string Path = CreatePathWithDate("/Upload/SellerAD/", "YY-MM:DD");
                modelAd.DefaultAdText = Path + System.Guid.NewGuid() + GetExt(upfile.Extension);
                upfile.SaveAs(Server.MapPath(modelAd.DefaultAdText)); //保存
            }
            #region 修改时候先把以前的广告删除
            if (old_AdModel == null)
            {
                nsb.AddErr("要修改的文件不存在。。"); nsb.ChkErr();
            }
            try
            {
                old_AdModel.DefaultAdText = Server.MapPath(old_AdModel.DefaultAdText);
                if (File.Exists(old_AdModel.DefaultAdText))
                {
                    File.Delete(old_AdModel.DefaultAdText);
                }
            }
            catch
            { }
            #endregion
        }
        #endregion

        modelAd.IsUsing = PageRequest.GetInt("IsUsing", 1) == 1 ? false : true;
        #endregion
        nsb.ChkErr();
        int RetFlag = bllAd.Update(modelAd);
        ManageHelper.AddLog("site_Adadd_" + SiteID, "修改了“" + modelAd.AdName + "”广告位。");

        KeRui.TemplateMaker.Publish publish = new KeRui.TemplateMaker.Publish();

        string publishInfo = publish.PublishAd(modelAd.AdID, 1);

        if (publishInfo != "")
        {
            nsb.AddErr("数据已经添加到数据库。ERROR：" + publishInfo); nsb.ChkErr();
        }

        Response.Write("<script>location.href=\"Adlist.aspx?siteID=" + modelAd.SiteID + "&sucmsg=修改成功。\";</script>");
    }
    #endregion

    #region 删除
    private void Del()
    {
        ManageHelper.CheckAdminPower("site_Addelete_" + SiteID);//权限
        int siteID = PageRequest.GetInt("siteID", -1);
        int UserID = PageRequest.GetInt("ID", -1);
        if (UserID == -1)
        {
            nsb.AddErr("该站点不存在。");
            nsb.ChkErr();
        }
        bllAd.Delete(UserID);
        ManageHelper.AddLog("site_Adadd_" + SiteID, "删除了“" + modelAd.AdName + "”商户。");
        Response.Redirect("AdList.aspx?state=" + state + "&siteID=" + siteID + "&sucmsg=恭喜。删除成功。");
    }
    #endregion

    #region 解锁和锁定
    private void State()
    {
        int UserID = PageRequest.GetInt("ID", -1);
        int st = PageRequest.GetInt("st", 0);
        if (UserID == -1)
        {
            nsb.AddErr("对不起。你想要操作的用户不存在。");
            nsb.ChkErr();
        }
        KeRui.BLL.Member bllMember = new KeRui.BLL.Member();
        int RetInt = bllMember.ChageState(UserID, 2);
        if (st == 1)
        {
            Response.Redirect("List.aspx?sucmsg=恭喜。锁定成功。");
        }
        else
        {
            Response.Redirect("List.aspx?sucmsg=恭喜。解锁成功。");
        }
    }
    #endregion

    #region 同步更新
    private void Ref()
    {
        int AdID = PageRequest.GetInt("ID", -1);
        int siteID = PageRequest.GetInt("siteID", -1);
        if (AdID == -1)
        {
            nsb.AddErr("非法访问。"); nsb.ChkErr();
        }
        if (bllAd.GetModel(AdID) == null)
        {
            nsb.AddErr("访问信息不存在。"); nsb.ChkErr();
        }
        bllAd.UpdateForSellerAd(AdID);

        Response.Redirect("adlist.aspx?siteID=" + siteID + "");
    }
    #endregion


    #region 根据日期创建文件夹
    public string CreatePathWithDate(string strV, string strT)
    {
        string uploadpath = "", s = "";

        //替换strT里的年月日伪字符
        if (strT.IndexOf(":") >= 0)
        {
            string[] strTs = strT.Split(":".ToCharArray());
            for (int i = 0; i < strTs.Length; i++)
            {
                strTs[i] = strTs[i].Replace("YY", DateTime.Now.Year.ToString());
                strTs[i] = strTs[i].Replace("MM", DateTime.Now.Month.ToString());
                strTs[i] = strTs[i].Replace("DD", DateTime.Now.Day.ToString());
                if (i != strTs.Length)
                {
                    uploadpath = uploadpath + strTs[i] + "/";
                }
                else
                {
                    uploadpath = uploadpath + strTs[i];
                }
                DirectoryInfo Fsofolder = new DirectoryInfo(Server.MapPath(strV + uploadpath));
                if (!Fsofolder.Exists)
                {
                    Fsofolder.Create();
                }
            }
            s = strV + uploadpath;
        }
        else
        {
            uploadpath = strT.Replace("YY", DateTime.Now.Year.ToString());
            uploadpath = uploadpath.Replace("MM", DateTime.Now.Month.ToString());
            uploadpath = uploadpath.Replace("DD", DateTime.Now.Day.ToString());
            DirectoryInfo Fsofolder = new DirectoryInfo(Server.MapPath(strV + uploadpath));
            if (!Fsofolder.Exists)
            {
                Fsofolder.Create();
                s = strV + uploadpath + "/";
            }
        }
        return s;
    }
    private string GetExt(string filePath)
    {
        return filePath.Substring(filePath.LastIndexOf("."));
    }
    /// <summary>
    /// 判断后缀名
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <param name="type">0.图片 1.Flash</param>
    /// <returns>True Or Flase</returns>
    private bool ChkExt(string filePath, int type)
    {
        bool flag = false;
        string ext = GetExt(filePath);
        string Exts = "";
        if (type == 0)//图片
        {
            Exts = ".jpg.gif.jpeg.jpe.png.bmp";
        }
        else if (type == 1)
        {
            Exts = ".swf";
        }
        if (Exts.IndexOf(ext.ToLower()) != -1)
        {
            flag = true;
        }
        return flag;
    }
    #endregion
}
